package com.example.demo.web.chat.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Result;
import org.noear.solon.web.sse.SseEmitter;
import org.noear.solon.web.sse.SseEvent;

/**
 * @author airhead
 */
@Component
@Slf4j
public class ChatService {
  static Map<String, SseEmitter> emitterMap = new HashMap<>();

  public SseEmitter open(String id) {
    SseEmitter sseEmitter =
        new SseEmitter(60 * 1000L)
            .onCompletion(() -> emitterMap.remove(id))
            .onError(e -> log.error("初始化 sse 错误", e))
            .onInited(s -> emitterMap.put(id, s));

    try {
      sseEmitter.send("Ok");
    } catch (IOException e) {
      log.error("发送 sse 错误", e);
      throw new RuntimeException(e);
    }

    // 初始化后，才能使用
    return sseEmitter;
  }

  public String send(String id) {
    SseEmitter emitter = emitterMap.get(id);
    if (emitter == null) {
      return "No user: " + id;
    }

    String msg = "test msg -> " + System.currentTimeMillis();
    System.out.println(msg);
    try {
      emitter.send(msg);
      // reconnectTime 用于提示前端重连时间
      emitter.send(new SseEvent().id(Utils.guid()).data(msg).reconnectTime(1000L));
      emitter.send(ONode.stringify(Result.succeed(msg)));
    } catch (IOException e) {
      log.error("发送 sse 错误", e);
      throw new RuntimeException(e);
    }

    return "Ok";
  }

  public String close(String id) {
    SseEmitter emitter = emitterMap.get(id);
    if (emitter != null) {
      emitter.complete();
    }

    return "Ok";
  }
}
